package com.client.mikocompose.ui.modules.home

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.annotation.ExperimentalCoilApi
import com.google.accompanist.insets.statusBarsPadding
import com.google.accompanist.pager.ExperimentalPagerApi
import com.linx.playAndroid.R
import com.linx.playAndroid.model.BannerData
import com.linx.playAndroid.public.Banner
import com.linx.playAndroid.ui.theme.white
import com.linx.playAndroid.widget.NetImage
import com.zj.refreshlayout.SwipeRefreshLayout
import kotlinx.coroutines.delay
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt

/**
 * @Description:
 * @Author: 吴祖清
 * @CreateDate: 12.2.22 3:10 下午
 */
fun Modifier.angledGradient(colors: List<Color>, degrees: Float) = this.then(
    Modifier.drawBehind {
        val rad = (degrees * PI / 180).toFloat()
        val diagonal = sqrt(size.width * size.width + size.height * size.height)
        val centerOffsetX = cos(rad) * diagonal / 2
        val centerOffsetY = sin(rad) * diagonal / 2

        // negative so that 0 degrees is left -> right and 90 degrees is top -> bottom
        val startOffset = Offset(
            x = (center.x - centerOffsetX).coerceIn(0f, size.width),
            y = (center.y - centerOffsetY).coerceIn(0f, size.height)
        )
        val endOffset = Offset(
            x = (center.x + centerOffsetX).coerceIn(0f, size.width),
            y = (center.y + centerOffsetY).coerceIn(0f, size.height)
        )

        drawRoundRect(
            brush = Brush.linearGradient(
                colors = colors,
                start = startOffset,
                end = endOffset
            ),
            size = size,
            cornerRadius = CornerRadius(20f)
        )
    })

@Composable
fun HomeCompose() {
    Box(modifier = Modifier.fillMaxSize()) {
        Image(
            painter = painterResource(R.mipmap.bg_public_topbg),
            contentDescription = null,
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(375f / 384),
        )
        Column(modifier = Modifier.statusBarsPadding()) {
            topBar()
            Box(modifier = Modifier.weight(1f)) {
                BasicSample()
            }
        }
    }
}


@Composable
fun BasicSample() {
    val homeViewModel: HomeViewModel = viewModel()
    homeViewModel.getBannerData()
    val homeListData = homeViewModel.homeListData.observeAsState()
    var refreshing by remember { mutableStateOf(false) }
    LaunchedEffect(refreshing) {
        if (refreshing) {
            delay(2000)
            refreshing = false
        }
    }
    SwipeRefreshLayout(isRefreshing = refreshing, onRefresh = {
        refreshing = true
    }) {
        homeListData.value?.let { listData ->
            if (listData.isEmpty()) {
                Column(
                    Modifier.fillMaxSize(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.padding(16.dp),
                        progress = 0.4f,
                        color = Color.Green
                    )
                }
            } else {
                LazyColumn {
                    items(listData.size) {
                        val data = listData[it]
                        when (data.style) {
                            HomeStyle.ONE_GAME -> OneGameCompose(data = data.data as OneGameModel)
                            HomeStyle.TWO_GAME -> TwoGameCompose(data = data.data as TwoGameModel)
                            HomeStyle.BANNER -> BannerCompose(list = data.data as MutableList<BannerModel>)
                            HomeStyle.RANK -> RankCompose(data = data.data as RankItemModel)
                            HomeStyle.TITLE -> TitleCompose(data = data.data as TitleModel)
                        }
                    }
                }
            }
        }

    }
}

@OptIn(ExperimentalCoilApi::class)
@Composable
fun OneGameCompose(data: OneGameModel) {
    Box(
        Modifier
            .padding(horizontal = 15.dp)
            .fillMaxWidth()
    ) {
        Box(
            Modifier
                .padding(top = 10.dp)
                .fillMaxWidth()
                .aspectRatio(345f / 125)
                .clip(RoundedCornerShape(15.dp))
        ) {
            SingleGame(data = data)
        }
    }
}

@Composable
fun SingleGame(data: OneGameModel) {
    NetImage(
        url = "${data.gameInfo?.gameIcon}",
        modifier = Modifier.fillMaxSize(),
        roundedCorners = 15f
    )
    Column(verticalArrangement = Arrangement.Bottom, modifier = Modifier.fillMaxSize()) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(30.dp)
                .background(
                    brush = Brush.verticalGradient(
                        listOf(
                            Color(0x0025B5F9),
                            Color(0xFF25B5F9)
                        )
                    )
                )
                .padding(start = 15.dp, top = 12.dp)
        ) {
            Text(
                text = "${data.gameInfo?.gameName}",
                style = TextStyle(color = white, fontSize = 15.sp)
            )
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(30.dp)
                .background(Color(0xFF25B5F9))
                .padding(start = 15.dp, top = 5.dp)
        ) {
            Text(
                text = "${data.playNum}人在玩",
                style = TextStyle(color = Color(0x77FFFFFF), fontSize = 12.sp)
            )
        }
    }
}

@Composable
fun TwoGameCompose(data: TwoGameModel) {
    Box(
        Modifier
            .padding(horizontal = 15.dp)
            .fillMaxWidth()
    ) {
        Row(Modifier.padding(top = 10.dp)) {
            Box(
                Modifier
                    .weight(1f)
                    .aspectRatio(1f)
                    .clip(RoundedCornerShape(15.dp))
            ) {
                SingleGame(data = data.list!![0])
            }
            Spacer(modifier = Modifier.width(10.5.dp))
            Box(
                Modifier
                    .weight(1f)
                    .aspectRatio(1f)
                    .clip(RoundedCornerShape(15.dp))
            ) {
                SingleGame(data = data.list!![0])
            }
        }
    }
}

@Composable
fun TitleCompose(data: TitleModel) {
    Row(
        verticalAlignment = Alignment.CenterVertically, modifier = Modifier
            .fillMaxWidth()
            .padding(start = 15.dp, top = 10.dp, end = 15.dp)
            .height(57.dp)
            .background(Color(0x33acaaac))
    ) {
        Text(
            text = data.title,
            style = TextStyle(color = Color(0xFF171717), fontSize = 22.sp)
        )
        Spacer(modifier = Modifier.weight(1f))
        if (data.showArrow)
            Image(
                painter = painterResource(R.mipmap.icon_public_arrow_right),
                contentDescription = null,
                modifier = Modifier.size(15.dp),
            )
    }
}

@Composable
fun RankCompose(data: RankItemModel) {
    Box(
        modifier = Modifier
            .padding(start = 15.dp, top = 10.dp, end = 15.dp)
            .fillMaxWidth()
            .height(80.dp)
            .background(Color(0x33acaaac))
    ) {
        NetImage(url = data.backgroundUrl, modifier = Modifier.fillMaxSize())
        Row(verticalAlignment = Alignment.CenterVertically) {
            Box(
                Modifier
                    .padding(start = 7.5.dp, top = 2.5.dp)
                    .size(75.dp)
            ) {
                NetImage(
                    url = "${data.winUser?.icon}",
                    modifier = Modifier
                        .padding(5.5.dp)
                        .fillMaxSize()
                )
                NetImage(
                    url = data.frame,
                    modifier = Modifier
                        .fillMaxSize()
                )
            }
            Text(
                text = "${data.gameInfo?.gameName}",
                Modifier
                    .padding(start = 32.dp, end = 15.dp)
                    .weight(1f)
            )
            NetImage(
                url = "${data.gameInfo?.gameIcon}",
                modifier = Modifier
                    .size(64.dp),
                roundedCorners = 10f
            )
            Spacer(modifier = Modifier.width(width = 8.dp))
        }
    }
}

@OptIn(ExperimentalPagerApi::class, ExperimentalCoilApi::class)
@Composable
fun BannerCompose(list: MutableList<BannerModel>) {
    list.map { BannerData(it.imageUrl, it.role) }.let {
        Box(
            modifier = Modifier
                .padding(start = 15.dp, end = 15.dp, top = 10.dp)
                .fillMaxWidth()
                .height(80.dp)
                .clip(RoundedCornerShape(15.dp))
        )
        {
            Banner(it) { link ->
            }
        }
    }
}


@Composable
fun topBar() {
    Row(
        modifier = Modifier
            .height(50.dp)
            .fillMaxWidth()
            .padding(start = 15.dp, end = 15.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Image(
            painter = painterResource(R.mipmap.ic_account),
            contentDescription = null,
            modifier = Modifier.size(34.dp),
        )
        Column(
            modifier = Modifier
                .weight(1f)
                .padding(start = 6.dp)
        ) {
            Text("迪士尼在逃保安", style = TextStyle(fontSize = 13.sp, color = Color(0xFF2C2C2C)))
            Row(
                Modifier
                    .angledGradient(
                        listOf(
                            Color(0xFFFFEDB4),
                            Color(0x45FFEDB4),
                        ), 0f
                    ),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Image(
                    painter = painterResource(R.mipmap.icon_public_goldcoins),
                    contentDescription = null,
                    modifier = Modifier.size(15.dp),
                )
                Box(modifier = Modifier.width(3.dp))
                Text(
                    "33.9K",
                    style = TextStyle(color = Color(0xFFA36400), fontSize = 10.sp)
                )
                Box(modifier = Modifier.width(6.dp))
            }
        }
        Box(Modifier.size(25.dp)) {
            Image(
                painter = painterResource(R.mipmap.home_icon_mission),
                contentDescription = null,
                modifier = Modifier.size(25.dp),
            )
        }
        Box(modifier = Modifier.width(20.dp))
        Box(Modifier.size(25.dp)) {
            Image(
                painter = painterResource(R.mipmap.home_icon_signin),
                contentDescription = null,
                modifier = Modifier.size(25.dp),
            )
        }
    }
}